// #include <iostream>
// #include <unistd.h>
// #include <pthread.h>
// #include <cstring>
// #include <cstdio>
#include "Mutex.hpp"
#include <unistd.h>
#include <cstdio>
using namespace std;

#define NUM 5

int tickets = 10000;

// pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

class threadData
{
public:
    // threadData(const string &name, pthread_mutex_t *pmutex)
    //     : _name(name), _pmutex(pmutex)
    // {
    // }

    threadData(const string &name, Mutex *pmutex)
        : _name(name), _pmutex(pmutex)
    {
    }

public:
    string _name;
    // pthread_mutex_t *_pmutex;
    Mutex *_pmutex;
};

void *threadRun(void *arg)
{
    threadData *td = static_cast<threadData *>(arg);

    // 抢票

    // while (tickets > 0)
    // {
    //     pthread_mutex_lock(td->_pmutex);
    //     cout << td->_name << ": " << tickets-- << endl;
    //     pthread_mutex_unlock(td->_pmutex);
    // }

    while (true)
    {
        lockGuard lg(td->_pmutex);
        if (tickets > 0)
        {
            cout << td->_name << ": " << tickets-- << endl;
        }
        else
        {
            break;
        }
        usleep(1);
    }

    delete td;
    pthread_exit(nullptr);
}

int main()
{
    pthread_t tids[NUM];

    // 1.创建锁
    pthread_mutex_t mutex;
    // pthread_mutex_init(&mutex, nullptr);
    Mutex m(&mutex);

    for (int i = 0; i < NUM; i++)
    {
        char name[64] = {0};
        snprintf(name, sizeof(name), "thread-%d", i + 1);

        // threadData *td = new threadData(name, &mutex);
        threadData *td = new threadData(name, &m);
        
        pthread_create(tids + i, nullptr, threadRun, td);
    }

    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    // // 3.销毁锁
    // pthread_mutex_destroy(&mutex);

    return 0;
}